package com.gkj.blog.filter;

import com.gkj.blog.business.service.ArticleService;
import com.gkj.blog.business.service.IpLogService;
import com.gkj.blog.business.service.impl.IpLogServiceImpl;
import com.gkj.blog.business.vo.entity.IpLogVo;
import com.gkj.blog.framework.holder.RequestHolder;
import com.gkj.blog.framework.holder.SpringContextHolder;
import com.gkj.blog.persistence.mapper.IpLogMapper;
import com.gkj.blog.util.IpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

public class LogFilter implements Filter {
    private static Logger logger= LoggerFactory.getLogger(LogFilter.class);
    private IpLogService ipLogService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if(ipLogService==null){
            ipLogService=SpringContextHolder.getBean(IpLogService.class);
        }
        HttpServletRequest r= (HttpServletRequest) request;
        IpLogVo ipLogVo=new IpLogVo();
        ipLogVo.setSessionId(r.getSession().getId());
        ipLogVo.setUri(r.getRequestURI());
        synchronized (r.getSession()) {
            IpLogVo dbIpLogVo = ipLogService.getBySidAndUri(ipLogVo.getSessionId(), ipLogVo.getUri());
            if (dbIpLogVo == null) {
                String ip = IpUtil.getRealIp(r);
                ipLogVo.setIp(ip);
                ipLogVo.setArea(IpUtil.getAddr(ip));
                ipLogVo.setVisitNum(1);
                ipLogService.insert(ipLogVo);
            } else {
                dbIpLogVo.setVisitNum(dbIpLogVo.getVisitNum() + 1);
                ipLogService.update(dbIpLogVo);
                ipLogVo = dbIpLogVo;
            }
        }
        logger.info("来自 {} ip为{}访客，访问了{}  sessionID为{}",ipLogVo.getArea(),ipLogVo.getIp(),ipLogVo.getUri(),ipLogVo.getSessionId());
        chain.doFilter(request,response);
    }

    @Override
    public void destroy() {

    }
}
